import { SettingsService } from '@delon/theme';
import { Component, OnDestroy, Inject, Optional } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { SocialService, SocialOpenType, ITokenService, DA_SERVICE_TOKEN } from '@delon/auth';
import { ReuseTabService } from '@delon/abc';
import { environment } from '@env/environment';
import { UtilityService } from '../../../service/utils.service';
import {NzModalService, NzNotificationService} from 'ng-zorro-antd';
import { appConfig} from '../../../service/common';
import { MenuService, TitleService } from '@delon/theme';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { zip } from 'rxjs/observable/zip';
import 'rxjs/Rx';
import 'rxjs/add/operator/catch';

@Component({
    selector: 'passport-login',
    templateUrl: './login.component.html',
    styleUrls: [ './login.component.less' ],
    providers: [ SocialService ]
})
export class UserLoginComponent implements OnDestroy {
    form: FormGroup;
    error = '';
    type = 0;
    loading = false;
    loginData: any; // 后台给的data属性


    constructor(
        fb: FormBuilder,
        private router: Router,
        public msg: NzMessageService,
        private settingsService: SettingsService,
        private socialService: SocialService,
        private menuService: MenuService,
        private httpClient: HttpClient,
        // 自身方法
        private utilityService: UtilityService,
        private modal: NzModalService,
        private nznot: NzNotificationService,
        @Optional() @Inject(ReuseTabService) private reuseTabService: ReuseTabService,
        @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService) {
        this.form = fb.group({
            userName: [null, [Validators.required, Validators.minLength(1)]],
            password: [null, Validators.required],
            mobile: [null, [Validators.required, Validators.pattern(/^1\d{10}$/)]],
            captcha: [null, [Validators.required]],
            remember: [true]
        });
    }

    // region: fields

    get userName() { return this.form.controls.userName; }
    get password() { return this.form.controls.password; }
    get mobile() { return this.form.controls.mobile; }
    get captcha() { return this.form.controls.captcha; }

    // endregion

    switch(ret: any) {
        this.type = ret.index;
    }

    // region: get captcha

    count = 0;
    interval$: any;

    getCaptcha() {
        this.count = 59;
        this.interval$ = setInterval(() => {
            this.count -= 1;
            if (this.count <= 0)
                clearInterval(this.interval$);
        }, 1000);
    }

    // endregion

    login(err) {
        if (err.code !== '200') {
            this.loading = false;
            if(!err.code){
             err.code = '网络异常，请稍微再试！'
            }
            this.nznot.create('error', err.code, err.msg);
        }
        return Observable.throw(err); /* 返回新的流接下去走 */
    }
    // 点击提交方法
    submit() {
        this.error = '';
        if (this.type === 0) {
            this.userName.markAsDirty();
            this.password.markAsDirty();
            if (this.userName.invalid || this.password.invalid) return;
        } else {
            this.mobile.markAsDirty();
            this.captcha.markAsDirty();
            if (this.mobile.invalid || this.captcha.invalid) return;
        }
        // mock http
        this.loading = true;
        const obj = {
            userId: this.userName.value,
            password : this.password.value
        };
        this.utilityService.postData(appConfig.testUrl  + appConfig.API.login, obj)
            .catch(res => this.login(res))
            .mergeMap(loginData => { // 改成并行，把后台数据保存，同时去请求菜单，然后把请求的值带到下一个流
                this.loading = false;
                this.loginData = loginData; // 把后台给的值保存
                return   this.utilityService.getData('assets/app-data.json');
                // return   this.utilityService.getData(appConfig.ABFUrl + '/' + appConfig.API.menuData);
            })
            .subscribe(menu => {
                if (this.loginData.code === '200') {
                    this.reuseTabService.clear();
                    // 设置登陆的token
                    this.tokenService.set({
                        seniortoken: this.loginData.result.token,
                        name: this.loginData.result.userInfo.svnUser,
                        role: this.loginData.result.userInfo.role,
                        token: this.loginData.result.token,
                    });
                    if (this.loginData.result.userInfo.role === '开发组') {
                        this.menuService.add(menu.devMenu); // 所有权限菜单
                    } else {
                        this.menuService.add(menu.menu); // 所有权限菜单
                    }
                    this.router.navigate(['/']);
                } else {
                    this.nznot.create('error', this.loginData.code, this.loginData.msg);
                }
            });
    }

    // endregion

    ngOnDestroy(): void {
        if (this.interval$) clearInterval(this.interval$);
    }
}
